package com.css.fxfzypg.modules.model.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.BeanUtil;
import com.css.fxfzypg.modules.model.entity.IntensityAttenuation;
import com.css.fxfzypg.modules.model.repository.IntensityAttenuationRepository;
import com.css.fxfzypg.modules.model.service.IntensityAttenuationService;
import com.css.fxfzypg.modules.model.vo.IntensityAttenuationVO;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * @author Dbj
 * @date 2022年10月05日  14:03
 */
@Service
public class IntensityAttenuationServiceImpl implements IntensityAttenuationService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysRoleService roleService;

    @Resource
    SUserService sUserService;

    @Resource
    private IntensityAttenuationRepository intensityAttenuationRepository;

    @Resource
    private SysAreaService areaService;

    @Override
    public Map<String, Object> getPage(IntensityAttenuationVO vo, int curPage, int pageSize) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        vo.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
        String roleByUserId = roleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        for(Map roleMap:roleMaps){
            String roleCode =  (String)roleMap.get("roleCode");
            if(roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)){
                vo.setNation(true);
            }
        }
        if(vo.getNation()==null){
            vo.setNation(false);
        }
        Map<String, Object> page = intensityAttenuationRepository.findPage(vo, curPage, pageSize);
        List<IntensityAttenuation> intensityAttenuationList = (List<IntensityAttenuation>) page.get("rows");
        List<IntensityAttenuation> vos = new ArrayList<>(intensityAttenuationList.size());
        for(IntensityAttenuation intensity:intensityAttenuationList){
            IntensityAttenuation intensityAttenuation = new IntensityAttenuation();
            BeanUtil.copy(intensity,intensityAttenuation);
            vo.setProvince(areaMap.get(intensity.getProvince()));
            if(!"全部".equals(intensity.getCity())){
                StringBuilder buffer = new StringBuilder();
                List<String> cityList = Arrays.asList(intensity.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                intensityAttenuation.setCity(cityName.substring(0,cityName.length()-1));
            }
            intensityAttenuation.setProvince(areaMap.get(intensity.getProvince()));
            vos.add(intensityAttenuation);
            //casualty.setIsDefault("1".equals(casualty.getIsDefault())?"是":"否");
        }
        page.put("rows",vos);
        return page;
    }

    @Override
    public Map<String, Object> getPageForXczh(IntensityAttenuationVO vo, int curPage, int pageSize) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = vo.getUserId();//xczh
        vo.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
//        String roleByUserId = roleService.getRoleByUserId(userId);
//        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
//        for(Map roleMap:roleMaps){
//            String roleCode =  (String)roleMap.get("roleCode");
//            if(roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)){
//                vo.setNation(true);
//            }
//        }
        if(vo.getNation()==null){
            vo.setNation(false);
        }
        Map<String, Object> page = intensityAttenuationRepository.findPageForXczh(vo, curPage, pageSize);
        List<IntensityAttenuation> intensityAttenuationList = (List<IntensityAttenuation>) page.get("rows");
        List<IntensityAttenuation> vos = new ArrayList<>(intensityAttenuationList.size());
        for(IntensityAttenuation intensity:intensityAttenuationList){
            IntensityAttenuation intensityAttenuation = new IntensityAttenuation();
            BeanUtil.copy(intensity,intensityAttenuation);
            vo.setProvince(areaMap.get(intensity.getProvince()));
            if(!"全部".equals(intensity.getCity())){
                StringBuilder buffer = new StringBuilder();
                List<String> cityList = Arrays.asList(intensity.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                intensityAttenuation.setCity(cityName.substring(0,cityName.length()-1));
            }
            intensityAttenuation.setProvince(areaMap.get(intensity.getProvince()));
            vos.add(intensityAttenuation);
            //casualty.setIsDefault("1".equals(casualty.getIsDefault())?"是":"否");
        }
        page.put("rows",vos);
        return page;
    }

    @Override
    public IntensityAttenuation getModelById(String id) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        IntensityAttenuation intensityAttenuation = intensityAttenuationRepository.getModelById(id);
        intensityAttenuation.setProvince(areaMap.get(intensityAttenuation.getProvince()));
        if(!"全部".equals(intensityAttenuation.getCity())){
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(intensityAttenuation.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            intensityAttenuation.setCity(cityName.substring(0,cityName.length()-1));
        }
        return intensityAttenuation;
    }

    @Override
    public IntensityAttenuation getDefaultModel() {
        return intensityAttenuationRepository.getDefaultModel();
    }

    @Override
    public IntensityAttenuation getDefaultModelByModelName(String modelName) {
        return intensityAttenuationRepository.getDefaultModelByModelName(modelName);
    }

    @Override
    public IntensityAttenuation getModelByIdForCopy(String id) {
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        IntensityAttenuation intensity = intensityAttenuationRepository.getModelById(id);
        intensity.setModelName("");
        intensity.setIsDefault("0");
        intensity.setCity("");
        intensity.setProvince("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        intensity.setCreateUserId(userId);
        intensity.setCreateUserName(sUser.getUserName());
        intensity.setOrgId(sUser.getOrgId());
        intensity.setOrgName(orgMap.get(sUser.getOrgId()));
        intensity.setIsValid(YNEnum.Y.toString());
        return intensity;
    }

    @Override
    public List<IntensityAttenuation> getByDivision(String province, String city,int isNa) {
        return intensityAttenuationRepository.getByDivision(province,city,isNa);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IntensityAttenuation save(IntensityAttenuation intensityAttenuation) throws ParseException{
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        intensityAttenuation.setId(UUIDGenerator.getUUID());
        intensityAttenuation.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        intensityAttenuation.setCreateUserName(sUser.getUserName());
        intensityAttenuation.setCreateTime(new Date());
        intensityAttenuation.setOrgId(sUser.getOrgId());
        String orgName = orgMap.get(sUser.getOrgId());
        intensityAttenuation.setOrgName(orgName);
        intensityAttenuation.setIsValid(YNEnum.Y.toString());
        //获取省code
        String areaCode = areaService.getDivisionCodeById(intensityAttenuation.getProvince());
        areaCode =(String) JSONObject.parse(areaCode);
        intensityAttenuation.setProvinceCode(areaCode);
        String type = intensityAttenuation.getType();
        intensityAttenuation.setType(null == intensityAttenuation.getType()?"1":intensityAttenuation.getType());
        intensityAttenuationRepository.save(intensityAttenuation);
        return intensityAttenuation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(IntensityAttenuation intensityAttenuation) {
        IntensityAttenuation intensity = intensityAttenuationRepository.getModelById(intensityAttenuation.getId());
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(intensity.getCreateUserId())){
            throw new RuntimeException("修改失败，只能修改自己创建的模型");
        }
        BeanUtil.copy(intensityAttenuation,intensity);
        intensityAttenuation.setUpdateUserId(userId);
        intensityAttenuation.setUpdateTime(new Date());
        intensityAttenuationRepository.update(intensityAttenuation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id){
        IntensityAttenuation intensityAttenuation = intensityAttenuationRepository.getModelById(id);
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(intensityAttenuation.getCreateUserId())){
            throw new RuntimeException("删除失败，只能删除自己创建的模型");
        }
        intensityAttenuationRepository.delete(userId,new Date(),id);
    }

    @Override
    public IntensityAttenuation getModel1ById(String model1Id) {
        IntensityAttenuation intensityAttenuation = intensityAttenuationRepository.getModelById(model1Id);
        return intensityAttenuation;
    }
}
